#ifndef QPICKRESULTTREEMODEL_H
#define QPICKRESULTTREEMODEL_H

#include <QAbstractItemModel>
#include <QIcon>

// 用于存储扫描结果的数据模型

class QcPickResultTreeModel : public QAbstractItemModel
{
    Q_OBJECT

public:
    explicit QcPickResultTreeModel(QObject *parent = nullptr);

    // Header:
    QVariant headerData(int section,
                        Qt::Orientation orientation,
                        int role = Qt::DisplayRole) const override;

    // Basic functionality:
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
    QModelIndex parent(const QModelIndex &index) const override;

    Qt::ItemFlags flags(const QModelIndex &index) const override;

    bool hasChildren(const QModelIndex &parent) const override;

    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;

    // role = Qt::UserRole，返回filePath
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;

    void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;

    bool isGroupped() const;
    bool isGroupRoot(const QModelIndex &index) const;

    int groupCount() const { return groupped_ ? result_.size() : 0; }

    int groupSize(int groupIdx) const;

     QModelIndex treeIndex(int group, int item, int col = 0) const;

    void appendItem(int group, const QString& filePath);

    void removeItem(int group, int item);

    void removeGroup(int group);

    bool empty() const { return result_.empty(); }

    // 显示缩略图还是文件icon
    bool useThumbnail() const { return useThumbnail_; }
    void setUseThumbnail(bool b) { useThumbnail_ = b; }

private:

    struct KpItemData;
    using COMP_FN = std::function<int(const KpItemData&, const KpItemData&)>;
    void sort_(const COMP_FN& comp);

    // 解析第@column列的@role角色信息
    QVariant fetchData_(const KpItemData& item, int column, int role) const;

    void setChildrenCheckStates_(int group, bool checked);

private:
    struct KpItemData {
        QString filePath;
        int checkState{ Qt::Unchecked };
        QIcon thumb_; // 缓存的缩略图
        mutable QIcon icon; // 缓存的icon

        KpItemData(const QString& path);
    };

    struct KpGroupData {
        int checkedItems{ 0 };
        QList<KpItemData> items;
    };

    bool groupped_; // 是否分组?
    QList<KpGroupData> result_; // 用来存储扫描结果. 无分组模式下，result_.front().items存储数据

    bool useThumbnail_{ true }; // 若true，则对于图片文件的DecorationRole返回缩略图，否则返回标识文件类型的icon
};

#endif // QPICKRESULTTREEMODEL_H
